#pragma once

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <functional>
#include <arpa/inet.h>

#include "nocopy.hpp"
#include "InetAddr.hpp"
#include "Log.hpp"
#include "dict.hpp"

using namespace log_ns;
using func_t = std::function<const std::string(const std::string&)>;

static const int gsockfd = -1;
static const int glocalport = 8888;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR
};

class UdpServer : public nocopy
{
public:
    UdpServer(func_t func, const uint16_t localport = glocalport)
        : _sockfd(gsockfd), _localport(localport), _isrunning(0), _func(func)
    {
    }
    ~UdpServer()
    {
    }

    void InitServer()
    {
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "_socket error!\n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "SOCKET create success, _sockfd: %d\n", _sockfd);

        // bind sock and sorkaddr_in

        struct sockaddr_in local;
        local.sin_family = AF_INET;    
        local.sin_port = htons(_localport);                                                            
        local.sin_addr.s_addr = INADDR_ANY;
 
        int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "Bind Error!\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "Soacket Bind Success!\n");
    }

    void Start()
    {
        _isrunning = 1;
        char inbuffer[1024];
        while (_isrunning)
        {
            struct sockaddr_in peer;
            memset(&peer, 0, sizeof(peer));
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                inbuffer[n] = 0;
                InetAddr addr(peer);
                printf("[%s:%d]# %s\n", addr.Ip().c_str(), addr.Port(),inbuffer);

                std::string echo_string = _func(inbuffer);

                ssize_t m = sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, (struct sockaddr*)&peer, len);
            }
            else 
            {
                std::cout<<"recvfrom, error"<<std::endl;
            }

        }
    }

private:
    int _sockfd;
    uint16_t _localport;
    // std::string _localip;
    bool _isrunning;
    func_t _func;
};